const app = getApp();
var interval = null //倒计时函数
Page({
  data:{
    list:[],
    showModalStatus: false,
    showModalFirst:false,
    nowIndex:0,
    nowObj:{},
    money:'',
    count:0,
    countInt:0,
    len:0,
    disabled: true,
    disabled1: true,
    time: '获取验证码',
    currentTime: 61,
    test1: '',
    test: '',
    tax:0,
    poundage:0,
    paidIn:0,
    phoneNumber:'',
    phoneNumberAll:'',
    balance: 0,
    balanceInt:0,
    securityCode:'',
    remark: '',
    payPassWord: '',
    code:'',
    trueMoney:0,
    alltax:0,
    allpoundage:0,
    xiaoyu100:false,
    dayu50000:false,
    isbad:true,
  },
  onShow: function () {
    this.getInfo();
    this.getList();
  },
  getInfo:function(){
    let _this = this;
    // 用户信息
    let baseInfo = app.globalData.baseInfo;
    _this.setData({
      balance: _this.numFilter(baseInfo.balance),
      balanceInt: baseInfo.balance,
      phoneNumber: baseInfo.phoneNumber,
      phoneNumberAll: baseInfo.userName,
    })
  },
  getList:function(){
    const _this = this;
    wx.request({
      url: app.globalData.path + 'services/app/applets/TeamList',
      data: {},
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': 'Bearer ' + app.globalData.authorization
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.success) {
          let list = res.data.result;
          list.forEach(i => {
            i.isAct = false;
            i.tax = 0;
            i.poundage = 0;
            i.paidIn = 0;
            i.money = 0;
          })
          console.log(list)
          _this.setData({
            list:list
          })
        } else {
          wx.showToast({
            title: res.data.error.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 过滤器
  numFilter: function (val) {
    // 截取当前数据到小数点后两位
    // let realVal = Number(val).toFixed(2)
    // num.toFixed(2)获取的是字符串
    // return Number(realVal)
    if (val || val == 0) {
      val = val.toString().replace(/\$|\,/g, '');
      if (isNaN(val)) {
        val = "0";
      }
      let sign = (val == (val = Math.abs(val)));
      val = Math.floor(val * 100 + 0.50000000001);
      let cents = val % 100;
      val = Math.floor(val / 100).toString();
      if (cents < 10) {
        cents = "0" + cents
      }
      for (var i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
        val = val.substring(0, val.length - (4 * i + 3)) + ',' + val.substring(val.length - (4 * i + 3));
      }
      return (((sign) ? '' : '-') + val + '.' + cents);
    }
  },
  getTest: function () {
    this.setData({
      test1: '已向' + this.data.phoneNumber + '的手机号发送验证码'
    })
    console.log(this.data.test1);
    this.setData({
      testStatu: true,
      test: this.data.test1
    })
    if (!interval) {
      this.sendCode();
    }
  },
  sendCode: function () {
    const _this = this;
    this.settimeD();
    this.setData({
      disabled: true
    })
    wx.request({
      url: app.globalData.path + 'services/app/applets/SendSMSCode',
      data: {
        phoneNumber: this.data.phoneNumberAll,
        SendType: 3
      },
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': 'Bearer ' + app.globalData.authorization
      },
      success: function (res) {
        console.log(res.data)
        // console.log(res.data.success)
        // console.log(res.data.result.securityCode)
        if (res.data.success) {
          if (res.data.result.securityCode) {
            _this.setData({
              securityCode: res.data.result.securityCode
            })
            if (res.data.result.sendResultType == 2) {
              wx.showToast({
                title: '手机号不存在',
                icon: 'none',
                duration: 2000
              })
            } else if (res.data.result.sendResultType == 3) {
              wx.showToast({
                title: '操作频繁',
                icon: 'none',
                duration: 2000
              })
            } else if (res.data.result.sendResultType == 4 || res.data.result.sendResultType == 5) {
              wx.showToast({
                title: '短信模板错误',
                icon: 'none',
                duration: 2000
              })
            }
          }
        } else {
          wx.showToast({
            title: '发送失败，请重试',
            icon: 'none',
            duration: 2000
          })
          interval = clearInterval(interval)
          _this.setData({
            time: '重新发送',
            currentTime: 61,
            disabled: false
          })
        }
      }
    })
  },
  //倒计时
  settimeD: function () {
    var that = this;
    var currentTime = that.data.currentTime
    interval = setInterval(function () {
      currentTime--;
      that.setData({
        time: currentTime + '秒'
      })
      if (currentTime <= 0) {
        interval = clearInterval(interval)
        that.setData({
          time: '重新发送',
          currentTime: 61,
          disabled: false
        })
      }
    }, 1000)
  },
  remarks:function(e){
    this.setData({
      remark: e.detail.value
    })
  },
  getpayD: function (e) {
    this.setData({
      payPassWord: e.detail.value
    })
    //wx.hideKeyboard();
  },
  getcodeD: function (e) {
    this.setData({
      code: e.detail.value
    })
    // wx.hideKeyboard();
  },
  // 添加
  toAdd: function () {
    wx.navigateTo({
      url: '/pages/editteamuser/editteamuser',
    })
  },
  // 编辑
  toedit:function(e){
    let ind = e.currentTarget.dataset.index;
    let list = this.data.list;
    if (list[ind].isAct){
      this.setData({
        showModalFirst: true,
        nowIndex: ind,
        nowObj: list[ind],
        money: list[ind].money,
        tax: list[ind].tax,
        poundage: list[ind].poundage,
        paidIn: list[ind].paidIn,
        xiaoyu100: false,
        dayu50000: false
      })
    }
  },
  // 改状态
  tochange:function(e){
    console.log(e.currentTarget.dataset.index);
    const _this = this;
    let ind = e.currentTarget.dataset.index;
    let list = this.data.list;
    console.log(list[ind].isAct)
    if (!list[ind].isAct) {
      this.setData({
        showModalFirst: true,
        nowIndex:ind,
        nowObj:list[ind],
        money:'',
        tax: 0,
        poundage: 0,
        paidIn:0,
        xiaoyu100:false,
        dayu50000:false
      })
    }else{
      wx.showModal({
        title: "提示",
        content:"是否删除",
        success: function (res) {
          console.log(res.confirm)
          if (res.confirm) {
            list[ind].isAct = false;
            _this.setData({
              list: list
            })
            _this.getnewList();
          }
        }
      })
    }
  },
  // 数组循环
  getnewList:function(){
    let list = this.data.list;
    let count = 0;
    let len = 0;
    for(let i=0;i<list.length;i++){
      if(list[i].isAct){
        count += parseFloat(list[i].money);
        len++
      }
    }
    this.setData({
      count:this.numFilter(count),
      countInt:count,
      len:len
    })
  },
  // 关闭弹框
  closemodal: function () {
    this.setData({
      showModalStatus: false
    })
    interval = clearInterval(interval);
  },
  // 关闭弹框
  closemodalfirst: function () {
    this.setData({
      showModalFirst: false
    })
  },
  // 验证两位小数
  tzMoney(e) {
    let val = e.detail.value;
    let re = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
    if (e.detail.value) {
      if (e.detail.value != '.') {
        if (!re.test(e.detail.value)) {
          let a = this.clearNoNum(val);
          this.setData({
            money: a
          })
        } else {
          this.setData({
            money: e.detail.value
          })
        }
        if (this.data.money < 100){
          this.setData({
            xiaoyu100:true,
            dayu50000: false,
            isbad:true
          })
        } else if (this.data.money > 50000){
          this.setData({
            dayu50000: true,
            xiaoyu100: false,
            isbad: true
          })
        }else{
          this.setData({
            dayu50000: false,
            xiaoyu100: false,
            isbad: true
          })
        }
        this.getTax(e.detail.value);
      } else {
        let a = this.clearNoNum('0' + val);
        console.log(a);
        this.setData({
          money: a
        })
      }
    } else {
      this.setData({
        tax: 0,
        money:''
      })
    }
  },
  //计算个人税,手续费
  getTax: function (money) {
    const _this = this;
    console.log(_this.data.money);
    if (money != '') {
      wx.request({
        url: app.globalData.path + 'services/app/applets/IndividualTax',
        data: {
          money: money,
          userId: _this.data.nowObj.id
        },
        method: 'POST',
        header: {
          'content-type': 'application/json', // 默认值
          'Authorization': 'Bearer ' + app.globalData.authorization
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.success) {
            _this.setData({
              tax: res.data.result
            })
            wx.request({
              url: app.globalData.path + 'services/app/applets/CalculatePoundage',
              data: {
                amount: money,
              },
              method: 'POST',
              header: {
                'content-type': 'application/json', // 默认值
                'Authorization': 'Bearer ' + app.globalData.authorization
              },
              success: function (res) {
                console.log(res.data);
                if (res.data.success) {
                  _this.setData({
                    poundage: res.data.result.poundageAmount
                  })
                  let paidIn = parseFloat(money) - parseFloat(_this.data.tax) - parseFloat(_this.data.poundage);
                  _this.setData({
                    paidIn: paidIn.toFixed(2)
                  })
                  if (_this.data.money < 100) {
                    _this.setData({
                      xiaoyu100: true,
                      dayu50000: false,
                      isbad: true
                    })
                  } else if (_this.data.money > 50000) {
                    _this.setData({
                      dayu50000: true,
                      xiaoyu100: false,
                      isbad: true
                    })
                  } else {
                    _this.setData({
                      dayu50000: false,
                      xiaoyu100: false,
                      isbad: false
                    })
                  }
                } else {
                  wx.showToast({
                    title: res.data.error.message,
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            })
          } else {
            wx.showToast({
              title: res.data.error.message,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
  },
  // 两位小数
  clearNoNum(value) {
    value = value.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符  
    value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的  
    value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数  
    if (value.indexOf(".") < 0 && value != "") {
      value = parseFloat(value);
    }
    return value;
  },
  // 第一个弹框确认
  firstmodalSure:function(e){
    console.log(e.detail.value.money);
    if (e.detail.value.money){
      this.setData({
        showModalFirst:false
      })
      let list = this.data.list;
      list[this.data.nowIndex].money = e.detail.value.money;
      this.getTax(e.detail.value.money);
      list[this.data.nowIndex].tax = this.data.tax;
      list[this.data.nowIndex].poundage = this.data.poundage;
      list[this.data.nowIndex].paidIn = this.data.paidIn;
      list[this.data.nowIndex].isAct = true;
      this.setData({
        list : list
      })
      this.getnewList();
    }
  },
  toshowSecondModal:function(){
    if(this.data.len != 0){
      if(this.data.remark){
        if (this.data.countInt <= this.data.balanceInt){
          this.setData({
            showModalStatus: true,
            disabled1: true
          })
          this.getTest();
          this.gettruemoney();
        }else{
          wx.showModal({
            content: '余额不足',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
              }
            }
          });
        }
      }else{
        wx.showModal({
          content: '请填写备注信息',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
            }
          }
        });
      }
    }else{
      wx.showModal({
        content: '请选择提现成员',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
          }
        }
      });
    }
  },
  gettruemoney:function(){
    let list = this.data.list;
    let trueMoney = 0;
    let alltax = 0;
    let allpoundage = 0;
    for (let i = 0; i < list.length; i++) {
      if (list[i].isAct) {
        trueMoney += parseFloat(list[i].paidIn);
        alltax += list[i].tax;
        allpoundage += list[i].poundage;
      }
    }
    this.setData({
      trueMoney: trueMoney,
      alltax: alltax,
      allpoundage: allpoundage
    })
    console.log(trueMoney);
    console.log(alltax);
    console.log(allpoundage);
  },
  // 得到提交的数组
  getSumbitArr:function(){
    let list = this.data.list;
    let arr = [];
    for (let i = 0; i < list.length; i++) {
      if (list[i].isAct) {
        let obj = {};
        obj.money = list[i].money;
        obj.userId = list[i].id;
        arr.push(obj);
      }
    }
    console.log(arr);
    return arr;
  },
  // 提现
  topaysure: function () {
    const _this = this;
    _this.setData({
      disabled1: false
    })
    let arr = [];
    arr = this.getSumbitArr();
    wx.request({
      url: app.globalData.path + 'services/app/applets/TeamTransfer',
      data: {
        count : _this.data.len,
        remarks: _this.data.remark,
        payPassWord: _this.data.payPassWord,
        code: _this.data.code,
        securityCode: _this.data.securityCode,
        items: arr
      },
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': 'Bearer ' + app.globalData.authorization
      },
      success: function (res) {
        console.log(res.data);
        if (res.data.success) {
          _this.setData({
            state: true
          })
          _this.makesure();
        } else {
          wx.showToast({
            title: res.data.error.message,
            icon: 'none',
            duration: 2000
          })
          // _this.setData({
          //   showModalStatus: false
          // })
          _this.setData({
            disabled1: true
          })
          // _this.makesure();
        }
      }
    })
  },
  makesure: function () {
    wx.navigateTo({
      url: '../result/result?state=' + this.data.state + '&from=transferme'
    })
    this.setData({
      showModalStatus: false
    })
  },
})